package com.tian.core.redis;

import com.tian.core.utils.SerializeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import redis.clients.jedis.JedisCluster;

/**
 * redis 集群版操作
 * @author YangTao
 * @date 2025/4/18
 */
@Component
public class RedisCluster implements JedisManager {
    private static Logger logger = LoggerFactory.getLogger(RedisCluster.class);

//    @Autowired
    private JedisCluster jedisCluster;

    @Override
    public void set(String key, String value) {
        try{
            getJedisCluster().set(key,value);
        }catch (Exception ex){
            logger.error("redis set error",ex);
        }
    }

    @Override
    public void set(String key, String value, Integer seconds) {
        try{
            getJedisCluster().set(key,value);
            getJedisCluster().expire(key,seconds);
        }catch (Exception ex){
            logger.error("redis set error",ex);
        }
    }

    @Override
    public String get(String key) {
        String result = null;
        try{
            result =  getJedisCluster().get(key);
        }catch (Exception ex){
            logger.error("redis get error",ex);
        }
        return result;
    }

    @Override
    public void del(String key) {
        try{
            getJedisCluster().del(key);
        }catch (Exception ex){
            logger.error("redis delete error",ex);
        }
    }

    @Override
    public void expire(String key, Integer seconds) {
        try{
            getJedisCluster().expire(key,seconds);
        }catch (Exception ex){
            logger.error("redis expire error",ex);
        }
    }

    @Override
    public Long incr(String key,Long value) {
        Long result = null;
        try{
            result = getJedisCluster().incrBy(key,value);
        }catch (Exception ex){
            logger.error("redis incr error",ex);
        }
        return result;
    }

    @Override
    public void setObject(String key, Object object) {
        try{
//            getJedisCluster().set(key.getBytes(), SerializeUtil.serialize(object));
        }catch (Exception ex){
            logger.error("redis setObject error",ex);
        }
    }

    @Override
    public void setObject(String key, Object object, Integer seconds) {

    }

    @Override
    public Object getObject(String key) {
       String result = getJedisCluster().get(key);
        //如果查询没有为空
        if(null == result){
            return null;
        }
        //查询到了，反序列化
      return SerializeUtil.deserializationObject(result);
    }

    /**
     * 获取Jedis连接
     *
     * @return Jedis连接
     */
    private JedisCluster getJedisCluster() {
        return this.jedisCluster;
    }

}
